//
//  HandyJSONObject.swift
//  cabbage_serialization
//
//  Created by dfsx6 on 2021/9/6.
//

import UIKit
import HandyJSON



//MARK:-
class HandyJSONObject: NSObject, HandyJSON {

    enum ListItemMode: Int {
        case one    = 0
        case big    = 1
        case more   = 2
        case zero   = 3
    }

    public var id: Int?
    public var columnName: String?
    public var publishTime: Date?
    public var listItemMode: ListItemMode?

    required override init() {

    }

    func mapping(mapper: HelpingMapper) {
//        mapper <<< self.columnName <-- "column_name"

        mapper.specify(property: &columnName, name: "column_name")
        mapper.specify(property: &publishTime, name: "publish_time") { (string) -> Date? in
            if let seconds = Double(string) {
                return Date.init(timeIntervalSince1970: seconds)
            }
            return nil
        }
        mapper.specify(property: &listItemMode, name: "list_item_mode") { (string) -> ListItemMode? in
            if let mode = Int(string) {
                return ListItemMode.init(rawValue: mode)
            }
            return nil
        }
    }
}

//MARK:-
extension HandyJSONObject {
    
    override var description: String {
        var des = ""
        des += "\n id = \(String(describing: id))"
        des += "\n columnName = \(String(describing: columnName))"
        des += "\n publishTime = \(String(describing: publishTime))"
        des += "\n listItemMode = \(String(describing: listItemMode))"

        return des
    }

    
    public static func serialization() {
        
        guard let url = Bundle.main.url(forResource: "content", withExtension: "json") else {
            print("read cms json error")
            return
        }
        
        do {
            let data = try Data.init(contentsOf: url)
            serialization(from: data)
            
        } catch let error {
            print(error.localizedDescription)
        }

    }
    
    public static func serialization(from data: Data) {
        
        let string = String.init(data: data, encoding: .utf8)
        let object = HandyJSONObject.deserialize(from: string)
        print(object)
    }
}
